package com.a.l;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

public class KonkeServer extends Service {
    private String tag = "KonkeServer";
    private List<CallbackBean> mList;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("KonkeServer", "onCreate");
        mList = new ArrayList<>();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mIKonkeAidlInterface;
    }

    IKonkeAidlInterface.Stub mIKonkeAidlInterface = new IKonkeAidlInterface.Stub() {

        @Override
        public JWTResp getJwt(JWTReq req) throws RemoteException {
            Log.e(tag, "getJwt:" + req.toString());
            return JwtDomain.getJWT(req, KonkeServer.this);
        }

        @Override
        public void addJWTFromCallback(JWTReq req, IKonkeAidlCallback callback) throws RemoteException {
            JWTResp jwt = JwtDomain.getJWT(req, KonkeServer.this);
            if (jwt != null) {
                callback.result(jwt);
            }
            CallbackBean callbackBean = new CallbackBean(req, callback);
            mList.add(callbackBean);
        }

        @Override
        public void pushToken() throws RemoteException {
            if (!mList.isEmpty()) {
                for (CallbackBean bean : mList) {
                    JWTResp jwt = JwtDomain.getJWT(bean.getJWTReq(), KonkeServer.this);
                    if (jwt != null) {
                        bean.getIKonkeAidlCallback().result(jwt);
                    }
                }
            }
        }

    };

}
